package com.czmh.etc.onlinepubsys.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.onlinepubsys.constants.ue.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CarInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.model.EtcPayOrder;
import com.czmh.etc.onlinepubsys.model.EtcUser;
import com.czmh.etc.onlinepubsys.model.SysConfig;
import com.czmh.etc.onlinepubsys.request.ue.QueryOrderByVehicleRequest;
import com.czmh.etc.onlinepubsys.response.ue.ApiResponse;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcPayOrderService;
import com.czmh.etc.onlinepubsys.services.EtcUserInfoSevice;
import com.czmh.etc.onlinepubsys.services.IDistributedLocker;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICarInfoService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IObuService;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.ue.UeHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Copyright (C), 2017-2020
 * Author: Chenzj
 * Date: 2021-08-02
 * FileName: DealUeActiveJob
 * Description: 联合电子订单状态定时任务
 */
@Slf4j
@Component
public class DealUeActiveJob {
    @Autowired
    private IObuService obuService;

    @Autowired
    private ICarInfoService carInfoService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IDistributedLocker distributedLocker;

    @Autowired
    private ICurrentContextService currentContextService;

    @Autowired
    private EtcPayOrderService etcPayOrderService;

    @Autowired
    private EtcUserInfoSevice etcUserInfoSevice;

    @Autowired
    private EtcOrderService etcOrderService;

    @Scheduled(cron = "40 * * * * ? ")
    public void dealUeActive() {
        //判断是否开启分布式定时任务
        Object enable = redisUtil.get("job:DealUeActiveJob:dealUeActive1");
        String key = "job-key:DealUeActiveJob:dealUeActive1";
        if (enable == null || enable.toString().equalsIgnoreCase("1")) {
            // 尝试获取锁，等待5秒，自己获得锁后一直不解锁则10秒后自动解锁
            boolean isGetLock = distributedLocker.tryLock(key, TimeUnit.SECONDS, 1L, 5L);
            if (isGetLock) {
                //获取符合条件的用户流程信息
                QueryWrapper<CurrentContext> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("type", 4);
                queryWrapper.in("state", 3, 4);
                queryWrapper.eq("pay_mode", 1);
                List<CurrentContext> list = currentContextService.queryObjects(queryWrapper);
                if (!CollectionUtils.isEmpty(list)) {
                    for (int i = 0; i < list.size(); i++) {
                        CurrentContext currentContext = list.get(i);
                        //判断是否在流程当中
                        String jsonStr = currentContext.getJsonData();
                        JSONObject jsonObject = JSON.parseObject(jsonStr);
                        if (jsonObject == null) {
                            jsonObject = new JSONObject();
                        }
                        //判断是否提交订单
                        if (jsonObject.get("submitOrderStatus") != null && jsonObject.getString("submitOrderStatus").equalsIgnoreCase("1")) {
                            //是否激活状态
                            boolean isActive = false;
                            //查询已提交订单状态
                            String token = redisUtil.queryUeToken();
                            QueryOrderByVehicleRequest request = new QueryOrderByVehicleRequest();
                            CarInfo etcCarInfo = carInfoService.get(currentContext.getCarId());
                            if (etcCarInfo != null) {
                                request.setVehicleColor(String.valueOf(etcCarInfo.getVehColor()));
                                request.setVehiclePlate(etcCarInfo.getVehPlate());
                            }
                            //log.info("DealUeActiveJob-queryOrderByVehicle:{}", JSON.toJSONString(request));
                            ApiResponse r = UeHttpUtil.postNoLog(BusinessType.QUERY_ORDER_BY_VEHICLE, JSON.toJSONString(request), token);
                            //log.info("ApiResponse:{}", JSON.toJSONString(r));
                            if (r != null && r.getSuccess()) {
                                if (r.getSuccess()) {
                                    //查看是否激活
                                    if (r.getRspData() != null) {
                                        JSONObject rsp = JSON.parseObject(r.getRspData());
                                        JSONObject object = JSON.parseObject(rsp.getString("object"));
                                        if (object != null && object.getString("object") != null) {
                                            JSONArray jsonArray = JSON.parseArray(object.getString("object"));
                                            if (jsonArray != null && jsonArray.size() > 0) {
                                                for (int j = 0; j < jsonArray.size(); j++) {
                                                    JSONObject jObject = (JSONObject) jsonArray.get(j);
                                                    if(jObject.getString("order_id").equalsIgnoreCase(jsonObject.getString("order_id"))){
                                                        if (jObject.getString("order_status") != null
                                                                && jObject.getString("order_status").equalsIgnoreCase("5")) {
                                                            isActive = true;
                                                            currentContext.setState(5);
                                                            currentContext.setObuId(jObject.getString("obuid"));
                                                            currentContext.setEtcCardNo(jObject.getString("cardno"));
                                                            //激活成功后判断是否有订金订单，有的话则直接把订单设置成待审核状态
                                                            QueryWrapper<EtcPayOrder> wrapper = new QueryWrapper<>();
                                                            LambdaQueryWrapper<EtcPayOrder> lambda = wrapper.lambda();
                                                            lambda.eq(EtcPayOrder::getDeleteFlag, 0);
                                                            lambda.eq(EtcPayOrder::getOrderSn, currentContext.getOrderNo());
                                                            EtcPayOrder etcPayOrder = etcPayOrderService.getOne(wrapper, true);
                                                            if(etcPayOrder != null){
                                                                etcPayOrder.setPayState(2);
                                                                etcPayOrder.setRefundApplyTime(new Date());
                                                                etcPayOrder.setUpdatedTime(new Date());
                                                                etcPayOrderService.updateById(etcPayOrder);
                                                            }
                                                            //激活成功后判断是否有前置订金订单，有的话则直接把订单设置成待审核状态，等待管理员审核之后给用户全额退款
                                                            EtcOrder etcOrder = etcOrderService.queryByOrderNo(currentContext.getOrderNo());
                                                            QueryWrapper<EtcPayOrder> wa = new QueryWrapper<>();
                                                            LambdaQueryWrapper<EtcPayOrder> lambdaQueryWrapper = wa.lambda();
                                                            lambdaQueryWrapper.eq(EtcPayOrder::getDeleteFlag, 0);
                                                            lambdaQueryWrapper.eq(EtcPayOrder::getPayState, 0);
                                                            lambdaQueryWrapper.eq(EtcPayOrder::getUserId, etcOrder.getUserId());
                                                            lambdaQueryWrapper.eq(EtcPayOrder::getProductSn, etcOrder.getBody());
                                                            EtcPayOrder payOrder = etcPayOrderService.getOne(wa, true);
                                                            if(payOrder != null){
                                                                payOrder.setPayState(2);
                                                                payOrder.setRefundApplyTime(new Date());
                                                                payOrder.setUpdatedTime(new Date());
                                                                etcPayOrderService.updateById(etcPayOrder);
                                                            }
                                                        }
                                                        if (jObject.getString("order_status") != null
                                                                && jObject.getString("order_status").equalsIgnoreCase("6")) {
                                                            log.info("主动取消-联合电子定时任务重置用户流程数据-重置前:{}", JSON.toJSONString(currentContext));
                                                            currentContext.setState(6);
                                                            currentContext.setDeleteFlag(1);
                                                            currentContextService.update(currentContext);
                                                            EtcOrder etcOrder = etcOrderService.queryByOrderNo(currentContext.getOrderNo());
                                                            EtcUser etcUser = etcUserInfoSevice.queryUserInfo(currentContext.getUserId());
                                                            log.info("联合电服取消订单同步逻辑删流程单数据:{}", JSON.toJSONString(currentContext));
                                                            log.info("联合电服取消订单同步物理删除订单数据:{}", JSON.toJSONString(etcOrder));
                                                            log.info("联合电服取消订单同步重置用户数据:{}", JSON.toJSONString(etcUser));
                                                            etcOrder.setPayState(3);
                                                            etcOrder.setBody(etcOrder.getBody() + "@" + currentContext.getId());
                                                            etcOrderService.updateById(etcOrder);
                                                            etcUser.setUser_loginname("");
                                                            etcUser.setUser_phone("");
                                                            etcUserInfoSevice.updateUser(etcUser);
                                                            log.info("主动取消-联合电子定时任务重置用户流程数据-重置后:{}", JSON.toJSONString(currentContext));
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if(r != null && r.getCode() != null && r.getCode().equalsIgnoreCase("20005")
                                    && r.getMsg() != null && r.getMsg().equalsIgnoreCase("订单不存在")){
                                log.info("订单不存在-联合电子定时任务重置用户流程数据-重置前:{}", JSON.toJSONString(currentContext));
                                currentContext.setState(1);
                                currentContext.setCarId(null);
                                currentContext.setApplyId(null);
                                currentContext.setFundAccountId(null);
                                currentContext.setJsonData(null);
                                currentContextService.update(currentContext);
                                log.info("订单不存在-联合电子定时任务重置用户流程数据-重置后:{}", JSON.toJSONString(currentContext));
                            }
                            //激活成功之后执行的逻辑
                            if (isActive) {
                                currentContextService.update(currentContext);
                                //按照铭创流程逻辑操作激活成功之后的操作
                                obuService.cmgActiveComplete(currentContext.getObuId(), currentContext.getUserId());
                            }
                        }
                    }
                }
            }
        }
    }
}
